import argparse
import logging
import os
from pathlib import Path

import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image
from torchvision import transforms
import datetime

from utils.data_loading import BasicDataset
from unet import UNet
from utils.utils import plot_img_and_mask


def predict_img(net,
                full_img,
                device,
                img_name,
                scale_factor=1,
                out_threshold=0.5):
    net.eval()
    img = BasicDataset.preprocess(None, full_img, scale_factor, is_mask=False)
    if args.is_edges:
        img = BasicDataset.edge_detection(img, img_name)

    img = torch.from_numpy(img)
    img = img.unsqueeze(0)
    img = img.to(device=device, dtype=torch.float32)

    with torch.no_grad():
        output = net(img).cpu()
        output = F.interpolate(output, (full_img.size[1], full_img.size[0]), mode='bilinear')
        if net.n_classes > 1:
            mask = torch.softmax(output, dim=1) >= out_threshold
            mask = mask.long().argmax(dim=1)
        else:
            mask = torch.sigmoid(output) > out_threshold

    return mask[0].long().squeeze().numpy()


def get_args():
    parser = argparse.ArgumentParser(description='Predict masks from input images')
    parser.add_argument('--model', '-m',
                        default='checkpoints/5_contrast+sampling+attention/best_checkpoint_epoch162_train0.0023_val0.9939.pth',
                        metavar='FILE',
                        help='Specify the file in which the model is stored')
    parser.add_argument('--input', '-i', metavar='INPUT', default='../../data/val/imgs', nargs='+',
                        help='Filenames of input images')
    parser.add_argument('--output', '-o', metavar='OUTPUT', default='pre_output', nargs='+',
                        help='Filenames of output images')
    parser.add_argument('--viz', '-v', action='store_true',
                        help='Visualize the images as they are processed')
    parser.add_argument('--no-save', '-n', action='store_true', default=False, help='Do not save the output masks')
    parser.add_argument('--mask_threshold', '-t', type=float, default=0.9,
                        help='Minimum probability value to consider a mask pixel white')
    parser.add_argument('--scale', '-s', type=float, default=1,
                        help='Scale factor for the input images')
    parser.add_argument('--bilinear', action='store_true', default=False, help='Use bilinear upsampling')
    parser.add_argument('--classes', '-c', type=int, default=2, help='Number of classes')
    parser.add_argument('--is_edges', '-ed', type=bool, default=True,
                        help='Is edge detection used for image preprocessing')

    return parser.parse_args()


def mask_to_image(mask: np.ndarray, mask_values):
    if isinstance(mask_values[0], list):
        out = np.zeros((mask.shape[-2], mask.shape[-1], len(mask_values[0])), dtype=np.uint8)
    elif mask_values == [0, 1]:
        out = np.zeros((mask.shape[-2], mask.shape[-1]), dtype=bool)
    else:
        out = np.zeros((mask.shape[-2], mask.shape[-1]), dtype=np.uint8)

    if mask.ndim == 3:
        mask = np.argmax(mask, axis=0)

    for i, v in enumerate(mask_values):
        out[mask == i] = v

    return Image.fromarray(out)


if __name__ == '__main__':
    args = get_args()
    logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')

    in_dir = args.input
    in_files_list = os.listdir(in_dir)
    out_dir = args.output

    if args.is_edges:
        net = UNet(n_channels=4, n_classes=args.classes, bilinear=args.bilinear)
    else:
        net = UNet(n_channels=3, n_classes=args.classes, bilinear=args.bilinear)

    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    logging.info(f'Loading model {args.model}')
    logging.info(f'Using device {device}')

    net.to(device=device)
    state_dict = torch.load(args.model, map_location=device)
    mask_values = state_dict.pop('mask_values', [0, 1])
    net.load_state_dict(state_dict)

    logging.info('Model loaded!')
    Path(out_dir).mkdir(parents=True, exist_ok=True)
    time_diff=[]
    for i, filename in enumerate(in_files_list):
        start_time = datetime.datetime.now()
        logging.info(f'Predicting image {filename} ...')
        img = Image.open(os.path.join(in_dir, filename))
        mask = predict_img(net=net,
                           full_img=img,
                           scale_factor=args.scale,
                           img_name=os.path.join(in_dir, filename),
                           out_threshold=args.mask_threshold,
                           device=device)

        end_time = datetime.datetime.now()
        time_diff.append((end_time-start_time).total_seconds()*1000)
        if not args.no_save:
            out_filename = os.path.join(out_dir, 'out_' + filename)
            result = mask_to_image(mask, mask_values)
            result = Image.blend(img, result, 0.4)
            result.save(out_filename)
            logging.info(f'Mask saved to {out_filename}')

        if args.viz:
            logging.info(f'Visualizing results for image {filename}, close to continue...')
            plot_img_and_mask(img, mask)

    logging.info(f'len:{len(time_diff)},min:{round(min(time_diff),4)} ms'
                 f',max:{round(max(time_diff[1:]),4)} ms'
                 f',mean time is {round(sum(time_diff[1:])/len(time_diff[1:]),4)} ms')##因为显卡的启动需要预热，所以需要将第一张图片的耗时剔除以后在计算平均耗时
